package BVRServer;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

public class ServerFrame extends JFrame
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
	
	private static int port = 10000;
	
	private Toolkit toolkit;
	
	private JPanel serverPanel;
	private JButton btnListen;
	private JButton btnClose;
	private JTextArea txtServerLog;
	private JScrollPane jspServerLog;
	
	private Calendar calendar = Calendar.getInstance();
	private SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_NOW);
	
	/**
	 * 
	 */
	public ServerFrame()
	{
		setSize(800, 600);
        setTitle("BvR:A Server");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        toolkit = getToolkit();
        
        serverPanel = new JPanel();
        getContentPane().add(serverPanel);
        
        CreateGUI();
        
        CenterFrameOnScreen();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		ServerFrame serverFrame = new ServerFrame();
		serverFrame.setVisible(true);
		
		BVRServerHandler.serverFrame = serverFrame;
		
		try
		{
			ByteBuffer.setUseDirectBuffers(false);
	        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

	        IoAcceptor acceptor = new SocketAcceptor();

	        SocketAcceptorConfig cfg = new SocketAcceptorConfig();
	        cfg.getFilterChain().addLast("logger", new LoggingFilter());
	        cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
	        
	        acceptor.bind(new InetSocketAddress(port), new BVRServerHandler(), cfg);
	        
	        serverFrame.appendLogText("Server started on port " + port);
		}
		catch (IOException e)
		{
			serverFrame.reportException(e);
		}
	}
	
	/**
	 * 
	 */
	public void CenterFrameOnScreen()
	{
        Dimension size = toolkit.getScreenSize();
        setLocation(size.width/2 - getWidth()/2, 
		size.height/2 - getHeight()/2);
	}
	
	/**
	 * 
	 * @return the current date and time in the given format
	 */
	private String getDateTimeNow(SimpleDateFormat format)
	{
		calendar = Calendar.getInstance();
		
		return format.format(calendar.getTime());
	}
	
	/**
	 * 
	 * @param text
	 */
	public void appendLogText(String text)
	{
		String entry = getDateTimeNow(dateFormat) + " - " + text + "\n";
		
		txtServerLog.append(entry);
		// autoscroll
		txtServerLog.setCaretPosition(txtServerLog.getDocument().getLength());
	}
	
	/**
	 * 
	 * @param e
	 */
	public void reportException(Throwable e)
	{
		appendLogText("EXCEPTION: " + e.toString());
		
		e.printStackTrace();
	}
	
	/**
	 * 
	 */
	private void StartServer()
	{
		
	}
	
	/**
	 * 
	 */
	private void CloseServer()
	{
		
	}
	
	/**
	 * 
	 */
	public void CreateGUI()
	{
		serverPanel.setLayout(null);
		
		btnListen = new JButton("Listen");
		btnListen.setSize(100, 35);
		btnListen.setLocation(15, 15);
		btnListen.setToolTipText("Start listening for incoming connections.");
		serverPanel.add(btnListen);
		
		btnClose = new JButton("Close");
		btnClose.setSize(100, 35);
		btnClose.setLocation(130, 15);
		btnClose.setToolTipText("Stop listening for incoming connections and close the server.");
		serverPanel.add(btnClose);
		
		txtServerLog = new JTextArea();
		txtServerLog.setEditable(false);
		
		jspServerLog = new JScrollPane(txtServerLog);
		jspServerLog.setSize(760, 400);
		jspServerLog.setLocation(15, 75);
		serverPanel.add(jspServerLog);
		
		btnListen.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent event)
			{
				StartServer();
			}
			
		});
		
		btnClose.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent event)
			{
				CloseServer();
			}
		});
	}

}
